#coding=utf-8
import xlrd
import logging
import sys
import importlib

importlib.reload(sys)

class ValueType:
	SrcValue = "src"
	IntValue = "int"
	FloatValue = "float"
	StringValue = "string"

class Key:
	def __init__(self, name, valueType, outputType, colNum, isPrimary):
		self.name = name
		self.isPrimary = isPrimary
		self.valueType = valueType
		self.outputType = outputType
		self.colNum = colNum

class SheetValue:
	def __init__(self, value, valueType):
		self.value = value
		self.valueType = valueType

	def Equals(self, sheetValue):
		return self.value == sheetValue.value and self.valueType == sheetValue.valueType

class SheetReader:
	def __init__(self, sheet, path, name):
		self._sheet = sheet
		self._rowCount = self._sheet.nrows
		self._colCount = self._sheet.ncols
		self._path = path
		self._name = name
		self._Read()

	def _Read(self):
		self._mapKey2config = {}

		self._listKey = []
		self._listPrimaryKey = []
		for colNum in range(0, self._colCount):
			name = str(self._sheet.cell(1, colNum).value).strip()
			if "#" in name:
				continue
			valueType = str(self._sheet.cell(2, colNum).value).strip()
			outputType = int(round(float(str(self._sheet.cell(3, colNum).value).strip())))
			isPrimary = False
			if "$" in name:
				isPrimary = True
				name = name[1:len(name)]
			key = Key(name, valueType, outputType, colNum, isPrimary)
			self._listKey.append(key)
			if isPrimary:
				self._listPrimaryKey.append(key)

		preKeyValue = {}
		for rowNum in range(5, self._rowCount):
			config = {}
			for keyIndex in range(0, len(self._listKey)):
				key = self._listKey[keyIndex]
				value = str(self._sheet.cell(rowNum, key.colNum).value).strip()
				if not len(value):
					continue
				if "#" in value:
					continue
				if key.isPrimary and len(value) == 0:
					value = preKeyValue[key.name]
				config[key.name] = SheetValue(value, key.valueType)
				preKeyValue[key.name] = value
			self._AddConfigToMap(self._mapKey2config, config, self._listPrimaryKey)

	def _AddConfigToMap(self, mapKey2Config, config, listPrimaryKey):
		key = listPrimaryKey[0]
		sheetValue = config[key.name]
		subMap = None
		for mapKey in mapKey2Config:
			if mapKey.Equals(sheetValue):
				subMap = mapKey2Config[mapKey]
				break

		listCount = len(listPrimaryKey)
		if listCount > 1:
			subList = listPrimaryKey[1:listCount]
			if subMap == None:
				subMap = {}
				mapKey2Config[sheetValue] = subMap
			self._AddConfigToMap(subMap, config, subList)
		else:
			mapKey2Config[sheetValue] = config

	def GetConfigMap(self):
		return self._mapKey2config